package com.mac.intellect_flow.admin.controller.monitor;

import com.mac.intellect_flow.constant.CommonConstant;
import com.mac.intellect_flow.framework.util.DictUtils;
import com.mac.intellect_flow.reply.R;
import com.mac.intellect_flow.sys.model.dto.SysCacheDto;
import com.mac.intellect_flow.sys.service.impl.SysConfigServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 缓存监控
 * 
 * @author mac
 */
@Tag(name = "缓存监控")
@RestController
@RequestMapping("/monitor/cache")
public class CacheController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private final static List<SysCacheDto> caches = new ArrayList<SysCacheDto>();{
        caches.add(new SysCacheDto(CommonConstant.ADMIN_LOGIN_TOKEN_KEY, "用户信息"));
        caches.add(new SysCacheDto(SysConfigServiceImpl.getCacheKey(), "配置信息"));
        caches.add(new SysCacheDto(DictUtils.getCacheKey(), "数据字典"));
        caches.add(new SysCacheDto(CommonConstant.CAPTCHA_CODE_KEY, "验证码"));
        caches.add(new SysCacheDto(CommonConstant.REPEAT_SUBMIT_KEY, "防重提交"));
        caches.add(new SysCacheDto(CommonConstant.PWD_ERR_CNT_KEY, "密码错误次数"));
    }

    @Operation(summary = "缓存监控信息")
    @PreAuthorize("@ps.hasPermi('monitor:cache:list')")
    @GetMapping()
    public R getInfo() throws Exception {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return R.success(result);
    }

    @Operation(summary = "缓存名称列表")
    @PreAuthorize("@ps.hasPermi('monitor:cache:list')")
    @GetMapping("/getNames")
    public R cache() {
        return R.success(caches);
    }

    @Operation(summary = "模糊查询缓存键列表")
    @PreAuthorize("@ps.hasPermi('monitor:cache:list')")
    @GetMapping("/getKeys/{cacheName}")
    public R getCacheKeys(@PathVariable String cacheName) {
        Set<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        Set<String> tempKeys = new HashSet<>();
        for (String cacheKey : cacheKeys){
            if (redisTemplate.type(cacheKey) == DataType.HASH){
                for (Object key : redisTemplate.opsForHash().keys(cacheKey)) {
                    if (key != null){
                        tempKeys.add(key.toString());
                    }
                }
            }
        }
        if (tempKeys.isEmpty()){
            return R.success(new TreeSet<>(cacheKeys));
        }
        return R.success(new TreeSet<>(tempKeys));
    }

    @Operation(summary = "查询缓存键值")
    @PreAuthorize("@ps.hasPermi('monitor:cache:list')")
    @GetMapping("/getValue/{cacheName}/{cacheKey}")
    public R getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey) {
        String cacheValue = "";
        if (redisTemplate.type(cacheName) == DataType.HASH){
            Object o = redisTemplate.opsForHash().get(cacheName, cacheKey);
            if (o != null){
                cacheValue = o.toString();
            }
        }else{
            cacheValue = redisTemplate.opsForValue().get(cacheKey);
        }
        SysCacheDto SysCacheDto = new SysCacheDto(cacheName, cacheKey, cacheValue);
        return R.success(SysCacheDto);
    }

    @Operation(summary = "由缓存名清空缓存")
    @PreAuthorize("@ps.hasPermi('monitor:cache:list')")
    @DeleteMapping("/clearCacheName/{cacheName}")
    public R clearCacheName(@PathVariable String cacheName)
    {
        Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        redisTemplate.delete(cacheKeys);
        return R.success();
    }

    @Operation(summary = "由缓存key清空缓存")
    @PreAuthorize("@ps.hasPermi('monitor:cache:list')")
    @DeleteMapping("/clearCacheKey/{cacheKey}")
    public R clearCacheKey(@PathVariable String cacheKey)
    {
        redisTemplate.delete(cacheKey);
        return R.success();
    }

    @Operation(summary = "清空所有缓存")
    @PreAuthorize("@ps.hasPermi('monitor:cache:list')")
    @DeleteMapping("/clearCacheAll")
    public R clearCacheAll()
    {
        Collection<String> cacheKeys = redisTemplate.keys("*");
        redisTemplate.delete(cacheKeys);
        return R.success();
    }
}
